package com.example.demo.controller;


import com.example.demo.RespStat;
import com.example.demo.bean.Account;
import com.example.demo.service.AccountService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liyao
 * @since 2021-04-13
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;

    @RequestMapping("/login")
    public String Login() {
        System.out.println("login");
        return "account/login";
    }


    /**
     * 用户登录异步校验
     *
     * @param loginName
     * @param password
     * @return
     */
    @RequestMapping("/validataAccount")
    @ResponseBody
    public String validataAccount(String loginName, String password, HttpServletRequest request) {
        System.out.println(loginName + "----" + password);
        Account account = accountService.findByLoginNameAndPassword(loginName, password);
        if (account == null) {
            return "登陆失败";
        } else {
            // 登录成功
            // 写到Session里
            // 在不同的controller 或者前端页面上 都能使用
            // 当前登录用户的Account对象
            request.getSession().setAttribute("account", account);
            return "success";
        }
    }

    @RequestMapping("/logout")
    public String logOut(HttpServletRequest request) {
        request.getSession().removeAttribute("account");
        return "index";
    }

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "3") int pageSize, Model model) {
        PageInfo<Account> page = accountService.findByPage(pageNum, pageSize);
        model.addAttribute("page", page);
        return "/account/list";
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public RespStat deleteById(int id) {
        //标记一下删除成功
        RespStat respStat = accountService.deleteById(id);
        return respStat;
    }
}

